<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋在线对战 - 登录</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <div class="auth-container fade-in">
            <div class="auth-header">
                <div class="auth-logo">🔴⚫</div>
                <h1>五子棋在线对战</h1>
            </div>
            
            <form id="loginForm">
                <div class="form-group">
                    <input type="text" class="form-control" id="username" placeholder="请输入账号" required>
                    <div class="error-message" id="username-error"></div>
                </div>
                
                <div class="form-group">
                    <input type="password" class="form-control" id="password" placeholder="请输入密码" required>
                    <div class="error-message" id="password-error"></div>
                </div>
                
                <div class="form-group">
                    <div class="error-message" id="form-error"></div>
                    <div class="success-message" id="form-success"></div>
                </div>
                
                <button type="submit" class="btn btn-primary" style="width: 100%;" id="loginBtn">
                    <span id="loginBtnText">登录</span>
                    <span id="loginBtnLoading" class="loading hidden"></span>
                </button>
                
                <div class="auth-footer">
                    <p>还没有账号？ <a href="register.html" class="auth-link">注册新账号</a></p>
                </div>
            </form>
            
            <div class="auth-footer">
                <p>五子棋在线对战 - 随时随地与棋友切磋</p>
                <p>&copy; 2025 五子棋在线对战平台</p>
            </div>
        </div>
    </div>

    <script>
        // 检查是否已登录
        document.addEventListener('DOMContentLoaded', function() {
            const token = localStorage.getItem('token');
            if (token) {
                // 验证token是否有效
                validateToken(token).then(valid => {
                    if (valid) {
                        window.location.href = 'hall.html';
                    } else {
                        localStorage.removeItem('token');
                        localStorage.removeItem('userInfo');
                    }
                });
            }
        });

        // 登录表单处理
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 清除之前的错误信息
            clearErrorMessages();
            
            // 获取表单数据
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            
            // 前端验证
            if (!validateForm(username, password)) {
                return;
            }
            
            // 显示加载状态
            showLoading(true);
            
            // 调用登录API
            login(username, password);
        });

        // 表单验证
        function validateForm(username, password) {
            let isValid = true;
            
            if (!username) {
                showError('username-error', '请输入账号');
                isValid = false;
            } else if (username.length < 3 || username.length > 20) {
                showError('username-error', '账号长度应为3-20个字符');
                isValid = false;
            }
            
            if (!password) {
                showError('password-error', '请输入密码');
                isValid = false;
            } else if (password.length < 8) {
                showError('password-error', '密码至少8位');
                isValid = false;
            }
            
            return isValid;
        }

        // 登录API调用
        async function login(username, password) {
            try {
                const response = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password
                    })
                });

                const result = await response.json();
                
                if (result.code === '1000') {
                    // 登录成功
                    const { token, userInfo } = result.data;
                    
                    // 保存到本地存储
                    localStorage.setItem('token', token);
                    localStorage.setItem('userInfo', JSON.stringify(userInfo));
                    
                    showSuccess('登录成功，正在跳转...');
                    
                    // 延迟跳转，让用户看到成功提示
                    setTimeout(() => {
                        window.location.href = 'hall.html';
                    }, 1000);
                } else {
                    // 登录失败
                    handleLoginError(result.code, result.message);
                }
            } catch (error) {
                console.error('登录请求失败:', error);
                showError('form-error', '网络连接失败，请检查网络连接');
            } finally {
                showLoading(false);
            }
        }

        // 处理登录错误
        function handleLoginError(code, message) {
            switch (code) {
                case '3001':
                    showError('username-error', '账号不存在');
                    break;
                case '3002':
                    showError('password-error', '密码错误');
                    break;
                case '3003':
                    showError('form-error', '账号或密码为空');
                    break;
                case '3004':
                    showError('form-error', '登录失败次数过多，请稍后再试');
                    break;
                default:
                    showError('form-error', message || '登录失败，请重试');
            }
        }

        // Token验证
        async function validateToken(token) {
            try {
                const response = await fetch('/api/auth/validate', {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                return response.ok;
            } catch (error) {
                return false;
            }
        }

        // 显示错误信息
        function showError(elementId, message) {
            const element = document.getElementById(elementId);
            if (element) {
                element.textContent = message;
                element.style.display = 'block';
            }
        }

        // 显示成功信息
        function showSuccess(message) {
            const element = document.getElementById('form-success');
            if (element) {
                element.textContent = message;
                element.style.display = 'block';
            }
        }

        // 清除错误信息
        function clearErrorMessages() {
            const errorElements = document.querySelectorAll('.error-message, .success-message');
            errorElements.forEach(el => {
                el.textContent = '';
                el.style.display = 'none';
            });
        }

        // 显示/隐藏加载状态
        function showLoading(isLoading) {
            const btn = document.getElementById('loginBtn');
            const btnText = document.getElementById('loginBtnText');
            const btnLoading = document.getElementById('loginBtnLoading');
            
            if (isLoading) {
                btn.disabled = true;
                btnText.style.display = 'none';
                btnLoading.classList.remove('hidden');
            } else {
                btn.disabled = false;
                btnText.style.display = 'inline';
                btnLoading.classList.add('hidden');
            }
        }

        // 输入框失焦时清除错误信息
        document.getElementById('username').addEventListener('blur', function() {
            if (this.value.trim()) {
                document.getElementById('username-error').textContent = '';
            }
        });

        document.getElementById('password').addEventListener('blur', function() {
            if (this.value) {
                document.getElementById('password-error').textContent = '';
            }
        });
    </script>
</body>
</html> 